<?php
/**
 * DotHerbert
 *
 * @package    db
 * @copyright  2009 extreme-programmers
 * @license    http://dotherbert.extreme-programmers.com/license   BSD License
 * @version    $Id:$
 */

namespace dotherbert\db;
use dotherbert\core;

/**
 * Database connection
 *
 * @package    db
 * @author     Johannes Trink <johannes.trink@extreme-programmers.com>
 */
class Connection
{
    /**
     * Instance
     *
     * @var Connection
     */
    private static $instance;

    /**
     * Pdo
     *
     * @var \PDO
     */
    private $pdo;

    /**
     * Get instance
     *
     * @return Connection
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Unset instance
     *
     * @return void
     */
    public static function unsetInstance()
    {
        self::$instance = null;
    }

    /**
     * Set instance
     *
     * @param Connections
     * @return void
     */
    public static function setInstance(Connection $connection)
    {
        self::$instance = $connection;
    }

    /**
     * Set pdo
     *
     * @param  \PDO
     * @return void
     */
    public function setPdo(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * Get pdo
     *
     * @return \PDO
     * @todo Trennen von Configurationsladen von Connection object
     */
    public function getPdo()
    {
        if (null === $this->pdo) {
            $this->pdo = $this->loadPdo();
        }
        return $this->pdo;
    }

    /**
     * Load pdo
     *
     * @return PDO
     */
    private function loadPdo()
    {
        $config = new \Zend_Config_Ini(implode(DIRECTORY_SEPARATOR,
                                               array(core\Environment::getModulesPath(),
                                                     core\Environment::getModule(),
                                                     'database.ini')),
                                       core\Environment::getApplicationEnvironment());
        $params = $config->params;

        $dsn = $config->get('adapter', 'pgsql')
             . ':host=' . $params->get('host')
             . ';port=' . $params->get('port', '5432')
             . ';dbname=' . $params->get('dbname')
             . ';user=' . $params->get('username')
             . ';password=' . $params->get('password');
        $connection = new \PDO($dsn);
        return $connection;
    }
}